package com.ymx.darling.spring.transaction;

import com.ymx.darling.exception.ExceptionFactory;
import com.ymx.darling.log.Log;
import com.ymx.darling.log.LogFactory;
import com.ymx.darling.transaction.Transaction;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @author 爱Java的小于
 */
public class SpringTransaction implements Transaction {
    private final Log log = LogFactory.getLog(SpringTransaction.class.getName());
    private Connection connection;
    private boolean isConnectionTransactional;
    private final DataSource dataSource;
    private boolean isAutoCommit;

    public SpringTransaction(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getConnection() {
        try {
            if (this.connection == null) {
                this.connection = DataSourceUtils.getConnection(dataSource);
                this.isAutoCommit = this.connection.getAutoCommit();
                this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource);
                if (this.log.isDebugEnabled()) {
                    this.log.debug("该JDBC连接[" + this.connection + "]" + (this.isConnectionTransactional ? "" : "不") + "由Spring事务管理");
                }
            }
            return this.connection;
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("获取数据库连接时抛出异常", e);
        }
    }

    public boolean getAutoCommit() {
        return this.isAutoCommit;
    }


    public boolean isClose() {
        try {
            return this.connection != null && this.connection.isClosed();
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("判断数据库连接是否关闭时抛出异常", e);
        }
    }

    public void commit() {
        try {
            if (this.connection != null && !this.isConnectionTransactional && !this.getAutoCommit()) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("正在提交 JDBC 连接 [" + this.connection + "]");
                }
                this.connection.commit();
            }
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("提交事务时抛出异常", e);
        }
    }

    public void close() {
        DataSourceUtils.releaseConnection(this.connection, this.dataSource);
    }

    public void rollBack() {
        try {
            if (this.connection != null && !this.isConnectionTransactional && !this.getAutoCommit()) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("正在回滚 JDBC 连接 [" + this.connection + "]");
                }
                this.connection.rollback();
            }
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("事务回滚时抛出异常", e);
        }
    }
}
